import { defineStore } from 'pinia'
import { LanguageEnum } from '../../enums/appEnums'
import { UserInfo } from '../../types/store';
import { useSettingStore } from './setting'
import { useWorktabStore } from './worktab'

interface UserState {
  language: LanguageEnum     // 语言
  isLogin: boolean           // 是否登录
  info: Partial<UserInfo>    // 用户信息
}

export const useUserStore = defineStore({
  id: 'userStore',
  state: (): UserState => ({
    language: LanguageEnum.CN,
    isLogin: false,
    info: {}
  }),
  getters: {
    getUserInfo(): Partial<UserInfo> {
      return this.info
    },
    getSettingState() {
      return useSettingStore().$state
    },
    getWorktabState() {
      return useWorktabStore().$state
    }
  },
  actions: {
    initState() {
      let sys: any = localStorage.getItem("sys")

      if(sys) {
        sys = JSON.parse(sys)
        let { info, isLogin, language } = sys.user
        this.info = info
        this.isLogin = isLogin
        this.language = language
      }
    },
    // 用户数据持久化存储
    saveUserData() {
      saveStoreStorage({
        user: {
          info: this.info,
          isLogin: this.isLogin,
          language: this.language,
          worktab: this.getWorktabState,
          setting: this.getSettingState
        }
      })
    },
    setUserInfo(info: UserInfo) {
      this.info = info
    },
    setLoginStatus(isLogin: boolean) {
      this.isLogin = isLogin
    },
    logOut() {
      document.getElementsByTagName("html")[0].removeAttribute('class') // 移除暗黑主题

      setTimeout(() => {
        this.info = {}
        this.isLogin = false
      }, 500)
    }
  }
})

function saveStoreStorage(sys: any) {
  localStorage.setItem("sys",  JSON.stringify(sys))
}